﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using CPETwit.Data.Entity;
using CPETwit.Web.Service.Implementation;
using CPETwit.Web.Service.Interface;
using Twitterizer.Entities;
using Twitterizer.Core;
using Twitterizer;
using System.Text.RegularExpressions;
using CPETwit.Web.Converter;

namespace CPETwit.Web.Pages
{
    public partial class Profil : System.Web.UI.Page
    {
        protected User currentUser = null;

        protected void Page_Load(object sender, EventArgs e)
        {
            this.isLoggedViaSession();

            /* Compteur d'abonnés, abonnements, tweets */
            ITwitterService twitterService = new TwitterService();
            IEnumerable<Tweet> tweets = twitterService.GetAllTweetsByUserId(((User)Session["login"]).id);
            this.nb_tweet.Text = tweets.Count().ToString();
            IEnumerable<User> users = twitterService.GetFollowers((User)Session["login"]);
            this.nb_abonne.Text = users.Count().ToString();
            IEnumerable<User> publishers = twitterService.GetPublishers((User)Session["login"]);
            this.nb_abonnement.Text = publishers.Count().ToString();

            /* Il se peut qu'on soit sur le profil de qqun d'autre */
            string loginRequested = Request.QueryString["login"];
            if (!String.IsNullOrEmpty(loginRequested))
            {
                this.currentUser = twitterService.GetUser(loginRequested);
            }
            else
            {
                this.currentUser = (User)Session["login"];
            }

            /* Compteur d'abonnés, abonnements, tweets si on se trouve sur le profil de qqun d'autre */
            if (this.currentUser != null && !((User)Session["login"]).login.Equals(loginRequested))
            {
                tweets = twitterService.GetAllTweetsByUserId(this.currentUser.id);
                users = twitterService.GetFollowers(this.currentUser);
                publishers = twitterService.GetPublishers(this.currentUser);
            }
            this.nb_tweet_profil.Text = tweets.Count().ToString();
            this.nb_abonne_profil.Text = users.Count().ToString();
            this.nb_abonnement_profil.Text = publishers.Count().ToString();
        }

        public static string parseTweet(String contenu)
        {
            if (String.IsNullOrEmpty(contenu))
            {
                return "";
            }

            string[] words = contenu.Split(' ');
            List<string> tags = new List<string>();
            string code_arrobase = "";
            String value = "";
            foreach (var item in words)
            {

                if (item.StartsWith("@"))

                    tags.Add(item);

            }
            foreach (var item in tags)
            {
                string value_arrobase = item.ToString();
                value = item.ToString();
                value = value.Substring(1, value.Length - 1);
                code_arrobase = "<a href=\"profil.aspx?login=" + value + "\">@" + value + "</a>";
                contenu = contenu.Replace(value_arrobase, code_arrobase);

            }

            
            string regex = @"((www\.|(http|https|ftp|news|file)+\:\/\/)[&#95;.a-zA-Z0-9-]+\.[a-zA-Z0-9\/&#95;:@=.+?,##%&~-]*[^.|\'|\# |!|\(|?|,| |>|<|;|\)])";
            string short_url = "";
            MatchCollection urls = Regex.Matches(contenu, regex);


            value ="";
            //string url;
            foreach (var item in urls)
            {
                value = item.ToString();

                short_url = "<a href=\"" + value + "\">" + value + "</a>";
                contenu = contenu.Replace(value, short_url);

            }

            

            return contenu;
        }

        public static string SecondsRemaining(DateTime? dt)
        {
            TimeConverter timeConverter = new TimeConverter();
            return timeConverter.Convert(dt.Value) as string;
        }


        /// <summary>
        /// Test si l'internaute est connecté ;
        /// Si ce n'est pas le cas, on le redirige vers la page d'accueil
        /// </summary>
        private void isLoggedViaSession()
        {
            bool isConnected = false;
            foreach (var item in Session.Keys)
            {
                if (String.Equals(item, "login"))
                {
                    isConnected = true;
                    /* Transmission du sexe de l'utilisateur */
                    String sexe = ((User)Session["login"]).sex;
                    Session.Add("sexe", sexe);
                    break;
                }
            }
            if (!isConnected)
            {
                Response.Redirect("connexion.aspx");
            }
        }

        /// <summary>
        /// Envoi de paramètres à l'ObjectDataSource
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void ObjectDataSourceProfilTimeline_Selecting(object sender, ObjectDataSourceSelectingEventArgs e)
        {
            if (this.currentUser == null)
            {
                Response.Redirect("timeline.aspx");
            }

            e.InputParameters["id"] = this.currentUser.id;
        }

        protected void DisconnectButton_Click(object sender, EventArgs e)
        {
            Session.Remove("login");
            Response.Redirect("connexion.aspx");
        }

        /// <summary>
        /// Gestion du remplissage de la ListView
        /// </summary>
        protected void ObjectDataSourceProfilTimeline_Created(Object sender, ListViewItemEventArgs e)
        {
            ListViewItem currentItem = e.Item;
            Tweet currentPublisher = (Tweet)currentItem.DataItem;
            
        }

        protected void DisconnectButtonProfil_Click(object sender, EventArgs e)
        {
            Session.Remove("login");
            Response.Redirect("connexion.aspx");
        }

        /// <summary>
        /// Action de tweeter
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void TweetButton_Click(object sender, EventArgs e)
        {
            ITwitterService twitterService = new TwitterService();
            twitterService.SaveTweet((User)Session["login"], this.TweetPost.Text, CheckBox_twitterizer.Checked);

            
            this.TweetPost.Text = "";

            Response.Redirect("profil.aspx");
        }

        protected void test(object sender, EventArgs e)
        {
            LinkButton b = sender as LinkButton;

            //throw new Exception("Pas encore implémenté - utiliser les surcharges d'EvenArgs");
            ITwitterService twitterService = new TwitterService();
            Tweet retweet = new Tweet();
            retweet = twitterService.getTweetFromId(Int64.Parse(b.CommandArgument)).FirstOrDefault();
            //retweet.twitter = ((User)Session["login"]).id;
            //retweet.message = Int64.Parse(b.CommandArgument);
            //retweet.tweetdate = new DateTime();
            //User u = new User();
            //u.id = ((User)Session["login"]).id;
            twitterService.ReTweet((User)Session["login"], retweet, CheckBox_twitterizer.Checked);
        }
    }
}